<template>
  <div class="app-container">
    <!-- 工具栏 -->
    <el-card class="filter-container">
      <el-row :gutter="20" class="mb8">
        <el-col :sm="24" :md="16" :lg="12">
          <div class="filter-item">
            <span class="filter-label">日期范围：</span>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              @change="handleDateRangeChange"
              style="width: 100%;" />
          </div>
        </el-col>
        <el-col :sm="24" :md="8" :lg="12" style="text-align: right">
          <el-button type="primary" icon="el-icon-setting" size="small"
                     @click="warningDialog = true">预警设置</el-button>
          <el-button type="success" icon="el-icon-download" size="small"
                     @click="handleExport">导出报表</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 库存统计概览 -->
    <el-row :gutter="20" class="panel-group">
      <el-col :span="6">
        <div class="card-panel">
          <div class="card-panel-description">
            <div class="card-panel-text">总库存量</div>
            <count-to :start-val="0" :end-val="overview.totalStock" :duration="2000"
                      class="card-panel-num" />
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="card-panel">
          <div class="card-panel-description">
            <div class="card-panel-text">本月入库量</div>
            <count-to :start-val="0" :end-val="overview.monthlyIn" :duration="2000"
                      class="card-panel-num" />
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="card-panel">
          <div class="card-panel-description">
            <div class="card-panel-text">本月出库量</div>
            <count-to :start-val="0" :end-val="overview.monthlyOut" :duration="2000"
                      class="card-panel-num" />
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="card-panel">
          <div class="card-panel-description">
            <div class="card-panel-text">库存预警数</div>
            <count-to :start-val="0" :end-val="overview.warningCount" :duration="2000"
                      class="card-panel-num warning" />
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 上半部分图表 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :lg="12">
        <div class="chart-wrapper">
          <div class="chart-header">
            <h3 class="chart-title">入库出库对比</h3>
          </div>
          <bar-chart ref="barChart" />
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="12">
        <div class="chart-wrapper">
          <div class="chart-header">
            <h3 class="chart-title">商品库存分布</h3>
          </div>
          <pie-chart ref="pieChart" />
        </div>
      </el-col>
    </el-row>

    <!-- 下半部分图表 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :lg="12">
        <div class="chart-wrapper">
          <div class="chart-header">
            <h3 class="chart-title">库存变动类型分布</h3>
          </div>
          <pie-chart ref="typeDistributionChart" />
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="12">
        <div class="chart-wrapper">
          <div class="chart-header">
            <h3 class="chart-title">库存变动类型趋势</h3>
          </div>
          <line-chart ref="typeTrendChart" :chart-data="typeTrendData" />
        </div>
      </el-col>
    </el-row>

    <!-- 预警设置对话框 -->
    <el-dialog title="预警设置" :visible.sync="warningDialog" width="500px" append-to-body>
      <el-form ref="warningForm" :model="warningForm" :rules="warningRules" label-width="100px">
        <el-form-item label="预警阈值" prop="threshold">
          <el-input-number v-model="warningForm.threshold" :min="1" :max="1000" controls-position="right"
                           style="width: 200px" />
          <span class="help-text">当库存数量低于此值时将触发预警</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateWarningThreshold">确 定</el-button>
        <el-button @click="warningDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CountTo from 'vue-count-to'
import LineChart from '@/components/Charts/LineChart'
import BarChart from '@/components/Charts/BarChart'
import PieChart from '@/components/Charts/PieChart'
import { getInventoryOverview, getInventoryTrend, getInventoryComparison, getInventoryCategory, updateWarningThreshold, exportAnalysisReport } from '@/api/stock/analysis'
import { getInventoryTypeDistribution, getInventoryTypeTrend } from '@/api/stock/analysis/type'

export default {
  name: 'InventoryAnalysis',
  components: {
    CountTo,
    LineChart,
    BarChart,
    PieChart
  },
  data() {
    return {
      dateRange: [],
      warningDialog: false,
      warningForm: {
        threshold: 10
      },
      warningRules: {
        threshold: [
          { required: true, message: '请输入预警阈值', trigger: 'blur' },
          { type: 'number', min: 1, max: 1000, message: '预警阈值必须在1-1000之间', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请输入预警阈值'));
              } else if (!Number.isInteger(value)) {
                callback(new Error('预警阈值必须为整数'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      },
      overview: {
        totalStock: 0,
        monthlyIn: 0,
        monthlyOut: 0,
        warningCount: 0
      },
      lineChartData: {
        labels: [],
        datasets: []
      },
      typeTrendData: {
        labels: [],
        datasets: []
      }
    }
  },
  created() {
    this.dateRange = [
      this.formatDate(new Date(new Date().setDate(1))),
      this.formatDate(new Date())
    ];
    this.getOverviewData();
    this.getTrendData();
    this.getComparisonData();
    this.getCategoryData();
    this.getTypeDistribution();
    this.getTypeTrendData();
  },
  methods: {
    async getOverviewData() {
      const response = await getInventoryOverview();
      if (response.code === 200) {
        this.overview = response.data;
      }
    },
    async getTrendData() {
      const params = {
        startDate: this.dateRange ? this.dateRange[0] : undefined,
        endDate: this.dateRange ? this.dateRange[1] : undefined
      };
      const response = await getInventoryTrend(params);
      if (response.code === 200) {
        this.lineChartData = response.data;
      }
    },
    async getComparisonData() {
      const params = {
        startDate: this.dateRange ? this.dateRange[0] : undefined,
        endDate: this.dateRange ? this.dateRange[1] : undefined
      };
      const response = await getInventoryComparison(params);
      if (response.code === 200) {
        this.$nextTick(() => {
          if (this.$refs.barChart) {
            this.$refs.barChart.setOptions(response.data);
          }
        });
      }
    },
    async getCategoryData() {
      const response = await getInventoryCategory();
      if (response.code === 200) {
        this.$nextTick(() => {
          if (this.$refs.pieChart) {
            this.$refs.pieChart.setOptions(response.data);
          }
        });
      }
    },
    async getTypeDistribution() {
      const params = {
        startDate: this.dateRange ? this.dateRange[0] : undefined,
        endDate: this.dateRange ? this.dateRange[1] : undefined
      };
      const response = await getInventoryTypeDistribution(params);
      if (response.code === 200) {
        this.$nextTick(() => {
          if (this.$refs.typeDistributionChart) {
            this.$refs.typeDistributionChart.setOptions(response.data);
          }
        });
      }
    },
    async getTypeTrendData() {
      const params = {
        startDate: this.dateRange ? this.dateRange[0] : undefined,
        endDate: this.dateRange ? this.dateRange[1] : undefined
      };
      const response = await getInventoryTypeTrend(params);
      if (response.code === 200) {
        this.typeTrendData = response.data;
        this.$nextTick(() => {
          if (this.$refs.typeTrendChart) {
            this.$refs.typeTrendChart.setOptions(this.typeTrendData);
          }
        });
      }
    },
    handleDateRangeChange() {
      this.getTrendData();
      this.getComparisonData();
      this.getTypeDistribution();
      this.getTypeTrendData();
    },
    async updateWarningThreshold() {
      const res = await updateWarningThreshold(this.warningForm);
      if (res.code === 200) {
        this.$modal.msgSuccess('预警阈值更新成功');
        this.warningDialog = false;
        this.getOverviewData();
      }
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    handleExport() {
      this.$confirm('是否确认导出库存分析报表?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$modal.loading("正在导出数据，请稍候...");
        // 准备查询参数
        const params = {
          startDate: this.dateRange && this.dateRange.length > 0 ? this.dateRange[0] : undefined,
          endDate: this.dateRange && this.dateRange.length > 1 ? this.dateRange[1] : undefined
        };

        // 使用API调用导出
        return exportAnalysisReport(params).then(response => {
          this.$modal.closeLoading();
          // 获取文件名
          const disposition = response.headers['content-disposition'];
          let filename = '库存分析报表.xlsx';
          if (disposition) {
            const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            const matches = filenameRegex.exec(disposition);
            if (matches != null && matches[1]) {
              filename = matches[1].replace(/['"]/g, '');
            }
          }

          // 创建blob并下载
          const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = filename;
          link.click();
          window.URL.revokeObjectURL(link.href);
          this.$modal.msgSuccess("导出成功");
        }).catch(err => {
          this.$modal.closeLoading();
          this.$modal.msgError("导出失败：" + (err.message || '未知错误'));
        });
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.panel-group {
  margin-top: 18px;

  .card-panel {
    height: 120px;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #666;
    background: #fff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, .08);
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 6px 16px rgba(0, 0, 0, .12);
    }
  }

  .card-panel-description {
    float: right;
    font-weight: bold;
    margin: 30px;
    margin-left: 0px;
    text-align: center;
    width: 100%;

    .card-panel-text {
      line-height: 22px;
      color: rgba(0, 0, 0, 0.65);
      font-size: 16px;
      margin-bottom: 16px;
      font-weight: normal;
    }

    .card-panel-num {
      font-size: 28px;
      font-weight: bold;

      &.warning {
        color: #f56c6c;
      }
    }
  }
}

.chart-wrapper {
  background: #fff;
  padding: 16px;
  margin-bottom: 32px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, .08);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 6px 16px rgba(0, 0, 0, .12);
  }
}

.app-container {
  padding: 20px;
  box-sizing: border-box;
  height: 100%;
  overflow-y: auto;
}

.mb8 {
  margin-bottom: 12px;
}

.panel-group {
  margin-top: 18px;
  margin-bottom: 20px;

  .card-panel {
    height: 120px;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #666;
    background: #fff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, .08);
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 6px 16px rgba(0, 0, 0, .12);
    }
  }

  .card-panel-description {
    font-weight: bold;
    margin: 0;
    padding: 30px 0;
    text-align: center;
    width: 100%;

    .card-panel-text {
      line-height: 22px;
      color: rgba(0, 0, 0, 0.65);
      font-size: 16px;
      margin-bottom: 16px;
      font-weight: normal;
    }

    .card-panel-num {
      font-size: 28px;
      font-weight: bold;

      &.warning {
        color: #f56c6c;
      }
    }
  }
}

.chart-wrapper {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, .08);
  transition: all 0.3s ease;
  height: 400px;
  overflow: hidden;
  position: relative;

  &:hover {
    box-shadow: 0 6px 16px rgba(0, 0, 0, .12);
  }
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .chart-wrapper {
    height: 350px;
  }
}

@media screen and (max-width: 768px) {
  .chart-wrapper {
    height: 300px;
    margin-bottom: 15px;
  }

  .panel-group .card-panel {
    height: 100px;
    margin-bottom: 10px;
  }

  .panel-group .card-panel-description {
    padding: 20px 0;
  }

  .panel-group .card-panel-description .card-panel-num {
    font-size: 24px;
  }
}

.filter-container {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-item {
  display: flex;
  align-items: center;
}

.filter-label {
  margin-right: 10px;
  font-weight: 500;
  color: #606266;
}

.mb8 {
  margin-bottom: 12px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.chart-title {
  margin: 0;
  padding: 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.chart-actions {
  display: flex;
  gap: 8px;
}

.el-table {
  margin-top: 16px;
}

.pagination-container {
  padding: 16px 0;
  text-align: right;
}
</style>
